import React, {useEffect} from "react";
import {
    BackHandler,
    FlatList,
    Text,
    TouchableOpacity,
    View,
} from "react-native";
import {useRouter} from "expo-router";
import styles from "./index.style";
import SessionItem from "@/components/Chat/ChatSessionList/SessionItem";
import {useTheme} from "@/contexts/ThemeContext";
import {ChatSession} from "@/types/chat-session";
import {useChatSessionActions, useChatSessionState} from "@/hooks/chat/chat-session";
import {useChatMessageActions} from "@/hooks/chat/chat-message";
import Ionicons from "@expo/vector-icons/Ionicons";
import {MaterialIcons} from "@expo/vector-icons";

/**
 * @author FlanChan
 */
const ChatSessionList = () => {
    const {colors} = useTheme();
    const router = useRouter();
    const {getSessions} = useChatSessionActions();
    const {sessions, enableMultipleSelect, selectedSessions} = useChatSessionState();
    const {deleteAllMessages} = useChatMessageActions()
    const {
        deleteSession,
        deleteBatchSessions,
        changeMultipleSelectMode,
        addSelectedSession,
        removeSelectedSession,
        unSelectBatchSessions,
        selectBatchSessions
    } = useChatSessionActions();

    // 监听硬件返回键
    const onBackPress = () => {
        if (!router.canGoBack()) {
            BackHandler.exitApp();
            return true;
        }
        changeMultipleSelectMode(false);
        return false;
    };

    useEffect(() => {
        getSessions();
    }, []);

    useEffect(() => {
        const backHandler = BackHandler.addEventListener(
            "hardwareBackPress",
            onBackPress
        );
        return () => backHandler.remove();
    }, [router, changeMultipleSelectMode]);

    const deleteSelectedAllSession = async () => {
        for (const sessionId of selectedSessions) {
            await deleteSession(sessionId);
            await deleteAllMessages(sessionId);
            removeSelectedSession(sessionId);
        }
        changeMultipleSelectMode(false);
    }

    return (
        <View style={[styles.container, {backgroundColor: colors.background}]}>
            <FlatList
                data={sessions}
                keyExtractor={(item: ChatSession) => String(item.sessionId)}
                renderItem={({item}: { item: ChatSession }) => (
                    <SessionItem session={item}/>
                )}
                ListEmptyComponent={
                    <View style={styles.emptyContainer}>
                        <Ionicons name="chatbubbles-outline" style={styles.emptyIcon}/>
                        <Text style={[styles.emptyText, {color: colors.text.secondary}]}>
                            暂无聊天会话，快去发起一次聊天吧～
                        </Text>
                        <TouchableOpacity
                            style={styles.emptyButton}
                            onPress={() => {
                                alert("功能开发中，敬请期待！")
                                //TODO 请使用模态对话框实现群聊和单聊的会话创建
                            }}
                        >
                            <Text style={styles.emptyButtonText}>开始聊天</Text>
                        </TouchableOpacity>
                    </View>
                }
            />
            {sessions.length > 0 && !enableMultipleSelect &&
                (
                    <View style={styles.fabContainer}>
                        <TouchableOpacity
                            style={[styles.editFab, {backgroundColor: colors.primary}]}
                            onPress={() => {
                                alert("功能开发中，敬请期待！")
                                //TODO 请使用模态对话框实现群聊和单聊的会话创建
                            }}
                        >
                            <MaterialIcons name="edit" size={26} color={colors.text.white}/>
                        </TouchableOpacity>
                    </View>
                )
            }
            {enableMultipleSelect && (
                <View
                    style={[styles.toolbar, {backgroundColor: colors.card.background}]}
                >
                    <TouchableOpacity
                        onPress={() => {
                            if (sessions.length === selectedSessions.length) {
                                // 如果当前已全选，则取消全选
                                unSelectBatchSessions(selectedSessions);
                            } else {
                                // 否则全选
                                selectBatchSessions(sessions.map((session) => session.sessionId));
                            }
                            selectBatchSessions(sessions.map((session) => session.sessionId))
                        }}
                    >
                        <Text
                            style={[styles.toolbarButton, {color: colors.text.primary}]}>{sessions.length === selectedSessions.length ? "取消全选" : "全选"}</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        onPress={deleteSelectedAllSession}>
                        <Text style={[styles.toolbarButton, {color: colors.status.error}]}>删除</Text>
                    </TouchableOpacity>
                </View>
            )}
        </View>
    );
};

export default ChatSessionList;
